package com.gky.gkytemplate.aop;

import com.gky.gkytemplate.annotation.AuthCheck;
import com.gky.gkytemplate.common.constant.UserConstant;
import com.gky.gkytemplate.common.context.BaseContext;
import com.gky.gkytemplate.common.enums.ErrorCode;
import com.gky.gkytemplate.common.enums.UserRoleEnum;
import com.gky.gkytemplate.common.exception.BusinessException;
import com.gky.gkytemplate.pojo.vo.UserLoginVo;
import com.gky.gkytemplate.utils.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


import javax.annotation.Resource;

@Aspect
@Component
@Slf4j
public class AuthInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.gky.gkytemplate.annotation.AuthCheck)")
    public void authPointcut() {
    }


    @Around("authPointcut()")
    public Object doInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AuthCheck authCheck = signature.getMethod().getAnnotation(AuthCheck.class);

        //方法执行需要的角色
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumsByValue(authCheck.mustRole());
        log.info("方法执行需要的角色:{}", mustRoleEnum);
        //登录用户所拥有的角色
        UserLoginVo user = (UserLoginVo) redisTemplate.opsForValue().get(UserConstant.USER_LOGIN + "_" + BaseContext.getCurrentId());
        System.out.println(user.toString());
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumsByValue(user.getUserRole());
        log.info("登录用户的角色:{}", userRoleEnum);
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }

        //1 没权限 或者 被封号
        ThrowUtils.throwIf(userRoleEnum == null || UserRoleEnum.BAN.equals(userRoleEnum), ErrorCode.NO_AUTH_ERROR);

        //2 需要有管理员权限
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum)) {
            if (!UserRoleEnum.ADMIN.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }

        return joinPoint.proceed();
    }


}
